<?php

require_once "./interface/IController.php";

class CourseController implements IController {
	private $view;
	
	public function __construct() {
		$this->view = new View ();
	}
	
	// 设置方法的访问权限，若权限不匹配，则调用 forbidAction()
	public function getAccessRule() {
		return array (//UserBean::$_ADMIN => array ("requestcourse", "requestlecture", "viewspecificcourse", "viewapprovingcourses", "viewapprovedcourses", "viewallcourses", "approvecourse", "to404", "editspecificcourse", "delete", "print" ), 
UserBean::$_SENATE => array ("requestcourse", "requestlecture", "viewspecificcourse", "viewapprovingcourses", "viewapprovedcourses", "viewallcourses", "approvecourse", "to404", "print" ), UserBean::$_INSTITUE => array ("requestcourse", "requestlecture", "viewspecificcourse", "viewapprovingcourses", "viewapprovedcourses", "viewallcourses", "approvecourse", "to404", "editspecificcourse", "delete", "print", "update" ), UserBean::$_GUEST => array ("to404", "forbid" ) );
	}
	
	public function requestCourseAction() {
		if (isset ( $_POST ["courseName"] )) {
			if (isset ( $_POST ["id"] )) {
				$this->updateCourse ();
			
		// 				$_GET ['action'] = "viewapprovingcourses";
			// 				$this->viewApprovingCoursesAction ();
			} else {
				if ($this->createNewCourse ( CourseBean::$_COURSE ))
					echo getAjaxResult ( true, "成功", "请在分类列表中查看新增条目！" );
				else
					echo getAjaxResult ( false, "失败", "数据未被保存！", "forbid" );
			
		// 				$_GET ['action'] = "viewapprovingcourses";
			// 				$this->viewApprovingCoursesAction ();
			}
			$_GET ['action'] = "viewapprovingcourses";
			$this->viewApprovingCoursesAction ();
		} else {
			$this->view->render ( "course_request.php" );
		}
	}
	
	public function requestLectureAction() {
		if (isset ( $_POST ["courseName"] )) {
			if (isset ( $_POST ["id"] )) {
				$this->updateCourse ();
			
		// 				$_GET ['action'] = "viewapprovingcourses";
			// 				$this->viewApprovingCoursesAction ();
			} else {
				if ($this->createNewCourse ( CourseBean::$_LECTURE ))
					echo getAjaxResult ( true, "成功", "请在分类列表中查看新增条目！" );
				else
					echo getAjaxResult ( false, "失败", "数据未被保存！", "forbid" );
			
		// 				$_GET ['action'] = "viewapprovingcourses";
			// 				$this->viewApprovingCoursesAction ();
			}
			$_GET ['action'] = "viewapprovingcourses";
			$this->viewApprovingCoursesAction ();
		} else {
			$this->view->render ( "lecture_request.php" );
		}
	}
	
	public function viewSpecificCourseAction() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
			setRollback ( "查看", 1, array ("id" => $id ) );
			
			$sql = "select * from course where id='$id'";
			$db = MysqliObj::getInstance ();
			$dbData = $db->fetch_array ( $sql );
			$data = new CourseBean ( $dbData );
		}
		$this->view->render ( "course_detail.php", $data, true );
	}
	
	public function editSpecificCourseAction() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
			setRollback ( "修改", 1, array ("id" => $id ) );
			
			$sql = "select * from course where id='$id'";
			$db = MysqliObj::getInstance ();
			$data = $db->fetch_array ( $sql );
			$data = new CourseBean ( $data );
			if (! ($data->department == $_SESSION ['userinfo'] ['department'] || isAdmin ())) {
				$data = new CourseBean ();
			}
		}
		$this->view->render ( "course_edit.php", $data, true );
	}
	
	public function deleteAction() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
			$sql = "select * from course where id='$id'";
			$db = MysqliObj::getInstance ();
			$data = $db->fetch_array ( $sql );
			$data = new CourseBean ( $data );
			if (($data->department == $_SESSION ['userinfo'] ['department'] || isAdmin ())) {
				$sql = "delete from course where id='$id'";
				$result = $db->query ( $sql );
				if ($result) {
					echo getAjaxResult ( true, "提示", "删除成功！" );
				}
			} else {
				echo getAjaxResult ( false, "错误", "未能成功删除！" );
			}
		
		}
		$this->viewApprovingCoursesAction ();
	}
	
	public function viewApprovingCoursesAction() {
		if (isset ( $_SESSION ['userinfo'] )) {
			$info = $_SESSION ['userinfo'];
			
			if (isset ( $_GET ['page'] )) {
				$page = $_GET ['page'];
			} else {
				$page = 1;
			}
			
			$pageSize = Sysconfig::getPageSize ();
			$begin = ($page - 1) * $pageSize;
			
			$sql = "";
			if (isAdmin () || isSenate ()) {
				$sql = "select * from `coursesystem`.`course` where approval='0' ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course` where approval='0' ";
			} else if (isInstitue ()) {
				$department = $info ['department'];
				$sql = "select * from `coursesystem`.`course` where department='$department' and approval='0' ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course` where department='$department' and approval='0'";
			}
			
			$db = MysqliObj::getInstance ();
			$resultArray = $db->fetch_arrays ( $sql );
			
			$courses = array ();
			if (! empty ( $resultArray )) {
				foreach ( $resultArray as $item ) {
					$courses [] = new CourseBean ( $item );
				}
			}
			
			$data = array ();
			$data ['currentPage'] = $page;
			$data ['courses'] = $courses;
			
			$result = $db->query ( $sqlForNum );
			if (! empty ( $result )) {
				$num = ( int ) ($result->num_rows / $pageSize);
				$data ['pageNum'] = $result->num_rows % $pageSize == 0 ? $num : $num + 1;
			} else {
				$data ['pageNum'] = 0;
			}
		}
		$data ['title'] = "正在处理";
		setRollback ( "正在处理", 0, (isset ( $data ['currentPage'] )) ? array ("page" => $data ['currentPage'] ) : array () );
		$this->view->render ( "course_list.php", $data );
	}
	public function viewApprovedCoursesAction() {
		if (isset ( $_SESSION ['userinfo'] )) {
			$info = $_SESSION ['userinfo'];
			
			if (isset ( $_GET ['page'] )) {
				$page = $_GET ['page'];
			} else {
				$page = 1;
			}
			
			$pageSize = Sysconfig::getPageSize ();
			$begin = ($page - 1) * $pageSize;
			
			if (isAdmin () || isSenate ()) {
				$sql = "select * from `coursesystem`.`course` where approval='1' ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course` where approval='1'";
			} else if (isInstitue ()) {
				$department = $info ['department'];
				$sql = "select * from `coursesystem`.`course` where department='$department' and approval='1' ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course` where department='$department' and approval='1'";
			}
			
			$db = MysqliObj::getInstance ();
			$resultArray = $db->fetch_arrays ( $sql );
			
			$courses = array ();
			if (! empty ( $resultArray )) {
				foreach ( $resultArray as $item ) {
					$courses [] = new CourseBean ( $item );
				}
			}
			
			$data = array ();
			$data ['currentPage'] = $page;
			$data ['courses'] = $courses;
			
			$result = $db->query ( $sqlForNum );
			if (! empty ( $result )) {
				$num = ( int ) ($result->num_rows / $pageSize);
				$data ['pageNum'] = $result->num_rows % $pageSize == 0 ? $num : $num + 1;
			} else {
				$data ['pageNum'] = 0;
			}
		}
		$data ['title'] = "已处理";
		setRollback ( "已处理", 0, (isset ( $data ['currentPage'] )) ? array ("page" => $data ['currentPage'] ) : array () );
		$this->view->render ( "course_list.php", $data );
	}
	
	// 查看所有课程申请
	public function viewAllCoursesAction() {
		if (isset ( $_SESSION ['userinfo'] )) {
			$info = $_SESSION ['userinfo'];
			
			if (isset ( $_GET ['page'] )) {
				$page = $_GET ['page'];
			} else {
				$page = 1;
			}
			
			$pageSize = Sysconfig::getPageSize ();
			$begin = ($page - 1) * $pageSize;
			
			if (isAdmin () || isSenate ()) {
				$sql = "select * from `coursesystem`.`course` ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course`";
			} else if (isInstitue ()) {
				$department = $info ['department'];
				$sql = "select * from `coursesystem`.`course` where department='$department' ORDER BY id DESC limit $begin, $pageSize";
				$sqlForNum = "select * from `coursesystem`.`course` where department='$department'";
			}
			
			$db = MysqliObj::getInstance ();
			$resultArray = $db->fetch_arrays ( $sql );
			
			$courses = array ();
			if (! empty ( $resultArray )) {
				foreach ( $resultArray as $item ) {
					$courses [] = new CourseBean ( $item );
				}
			}
			
			$data = array ();
			$data ['currentPage'] = $page;
			$data ['courses'] = $courses;
			
			$result = $db->query ( $sqlForNum );
			if (! empty ( $result )) {
				$num = ( int ) ($result->num_rows / $pageSize);
				$data ['pageNum'] = $result->num_rows % $pageSize == 0 ? $num : $num + 1;
			} else {
				$data ['pageNum'] = 0;
			}
		}
		$data ['title'] = "全部申请";
		setRollback ( "全部申请", 0, (isset ( $data ['currentPage'] )) ? array ("page" => $data ['currentPage'] ) : array () );
		$this->view->render ( "course_list.php", $data );
	
	}
	
	public function approveCourseAction() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
			$db = MysqliObj::getInstance ();
			$sql = "UPDATE `coursesystem`.`course` SET `approval` = '1' WHERE `course`.`id` = $id";
			$result = $db->query ( $sql );
			if ($result) {
				$data = true;
				echo getAjaxResult ( true, "提示", "该条目成功通过审批！" );
			}
		} else {
			$data = false;
			echo getAjaxResult ( false, "失败", "该条目可能不存在或者已通过审批！" );
		}
		
		$this->viewApprovedCoursesAction ();
	}
	
	public function printAction() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
			$sql = "select * from course where id='$id'";
			$db = MysqliObj::getInstance ();
			$data = $db->fetch_array ( $sql );
			if ($data) {
				$data = new CourseBean ( $data );
				$this->view->render ( "course_print.php", $data );
			}
		}
	}
	public function to404Action() {
		if ($_GET ['method'] != "ajax")
			$this->view->render ( "404.php" );
	}
	
	// 当请求的 action 不合法时调用此方法
	// 重载 IController 接口
	public function forbidAction() {
		
		if (isGuest () && $_GET ['method'] == "ajax") {
			echo getAjaxResult ( false, "提示", "登录超时，请从新登录", "login" );
		} elseif (isGuest ()) {
			redirectTo ( urlToAction ( 'user', 'login' ) );
		} else {
			echo getAjaxResult ( false, "警告", "您没有权限进行该操作！", "forbid" );
		}
	
		// $this->view->render ( "forbid.php" );
	}
	
	private function createNewCourse($type) {
		$courseName = $_POST ["courseName"];
		$department = $_POST ["department"];
		$teacherType = $_POST ["teacherType"];
		$teacherName = $_POST ["teacherName"];
		$organization = $_POST ["organization"];
		$jobTitle = $_POST ["jobTitle"];
		$credential = $_POST ["credential"];
		$courseBegin = $_POST ["courseBegin"];
		$courseEnd = $_POST ["courseEnd"];
		$salary = $_POST ["salary"];
		$salaryStandard = $_POST ["salaryStandard"];
		$salaryFix = $_POST ["salaryFix"];
		$time = $_POST ["time"];
		$unit = $_POST ["unit"];
		$courseType = $type;
		$new = true;
		$approval = false;
		$summaryTitle=(isset($_POST['summaryTitle']))?$_POST['summaryTitle']:"";
		$summary=$_POST['summary'];
		$serial = date("Ymd");
		$sqlForNum = "select id from course where serial regexp '^$serial'";
		
		
		// 		$course = new CourseBean();
		// 		$course->setCourseName($courseName);
		// 		$course->setDepartment($department);
		// 		$course->setTeacherType($teacherType);
		// 		$course->setTeacherName($teacherName);
		// 		$course->setOrganization($organization);
		// 		$course->setJobTitle($jobTitle);
		// 		$course->setCredential($credential);
		// 		$course->setCourseBegin($courseBegin);
		// 		$course->setCourseEnd($courseEnd);
		// 		$course->setSalary($salary);
		// 		$course->setSalaryStandard($salaryStandard);
		// 		$course->setTime($time);
		// 		$course->setUnit($unit);
		// 		$course->setCourseType($courseType);
		// 		$course->setNew($new);
		$dbms = MysqliObj::getInstance ();
		$result = $dbms->query($sqlForNum);
		$num = str_pad($result->num_rows+1, 4, '0',STR_PAD_LEFT);
		$serial.=$num;
		$sql = "INSERT INTO course(courseName, courseType, department, teacherType, teacherName, organization, jobTitle, credential, courseBegin, time, unit, salary, courseEnd, new, approval, salaryStandard, salaryFix, summaryTitle, summary,serial) VALUES('$courseName', '$courseType', '$department', '$teacherType', '$teacherName', '$organization', '$jobTitle', '$credential', '$courseBegin', '$time', '$unit', '$salary', '$courseEnd', '$new', '$approval','$salaryStandard','$salaryFix','$summaryTitle','$summary', '$serial')";
		$dbms->real_escape_string ( $sql );
		$result = $dbms->query ( $sql );
		if ($result) {
			return true;
		} else {
			return false;
		}
	}
	
	private function updateCourse() {
		$id = $_POST ["id"];
		$courseName = $_POST ["courseName"];
		$department = $_POST ["department"];
		$teacherType = $_POST ["teacherType"];
		$teacherName = $_POST ["teacherName"];
		$organization = $_POST ["organization"];
		$jobTitle = $_POST ["jobTitle"];
		$credential = $_POST ["credential"];
		$courseBegin = $_POST ["courseBegin"];
		$courseEnd = $_POST ["courseEnd"];
		$salary = $_POST ["salary"];
		$salaryStandard = $_POST ["salaryStandard"];
		$salaryFix = $_POST ["salaryFix"];
		$time = $_POST ["time"];
		$unit = $_POST ["unit"];
		$courseType = $_POST ["courseType"];
		$summaryTitle=(isset($_POST['summaryTitle']))?$_POST['summaryTitle']:"";
		$summary=$_POST['summary'];
		
		// 		$course = new CourseBean();
		// 		$course->setCourseName($courseName);
		// 		$course->setDepartment($department);
		// 		$course->setTeacherType($teacherType);
		// 		$course->setTeacherName($teacherName);
		// 		$course->setOrganization($organization);
		// 		$course->setJobTitle($jobTitle);
		// 		$course->setCredential($credential);
		// 		$course->setCourseBegin($courseBegin);
		// 		$course->setCourseEnd($courseEnd);
		// 		$course->setSalary($salary);
		// 		$course->setSalaryStandard($salaryStandard);
		// 		$course->setTime($time);
		// 		$course->setUnit($unit);
		// 		$course->setCourseType($courseType);
		// 		$course->setNew($new);
		$dbms = MysqliObj::getInstance ();
		$sql = "UPDATE `coursesystem`.`course` SET `courseName`='$courseName', approval` = '0', `teacherType`='$teacherType', `teacherName`='$teacherName', `organization`='$organization', `jobTitile`='$jobTitle',
		`credential`='$credential', `courseBegin`='$courseBegin', `courseEnd`='$courseEnd', `salary`='$salary', `salaryStandard`='$salaryStandard',`salaryFix`=$salaryFix ,`time`='$time', `unit`='$unit', `courseType`='$courseType', `summaryTitle`='$summaryTitle', `summary`='$summary'
		WHERE `course`.`id` = $id ";
		$dbms->real_escape_string ( $sql );
		$result = $dbms->query ( $sql );
		if ($result) {
			return true;
		} else {
			return false;
		}
	}
	
	function updateAction() {
		if (isset ( $_POST ['id'] )) {
			$id = $_POST ['id'];
			$course = CourseBean::findById ( $id );
			if ($course == null) {
				echo getAjaxResult ( false, "提示", "该条信息不存在或者不可被修改，请刷新后再试！" );
			} elseif ($course->approval == 1) {
				echo getAjaxResult ( false, "提示", "该条信息以通过审核，请刷新后再试！" );
			} elseif ($course->department != $_SESSION ['userinfo'] ['department'] || isAdmin ()) {
				echo getAjaxResult ( false, "提示", "您无法进行该操作！" );
			} else {
			}
			$this->updateCourse ();
		}
		$_GET ['action'] = "viewapprovingcourses";
		$this->viewApprovingCoursesAction ();
	
	}
}

?>